package com.lvw.weather.city.web;

import com.lvw.weather.city.service.ICityService;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.logging.Logger;

@RestController
public class CityController {

    private final Logger log = Logger.getLogger(getClass().toString());

    @Autowired
    private DiscoveryClient client;

    @Autowired
    /*@Qualifier("cityServiceHystrixRough")*/
    @Qualifier("cityServiceSimple")
    private ICityService cityService;

    @RequestMapping("/sys/services")
    public String sys() {

        StringBuilder sb = new StringBuilder();
        client.getServices().forEach(s -> {
            sb.append("---Service: " + s);
            sb.append("\r\n");
            log.info("---Service: " + s);
        });

        return sb.toString();

    }

    @RequestMapping("/city")
    public String city() {
        return "beijing";
    }

    @RequestMapping(value = "/city/{city}/forcast", method = RequestMethod.GET)
    public String cityForcast(@PathVariable String city) {

        // 开启HystrixRequestContext, 用于缓存
        HystrixRequestContext.initializeContext();

        long start = System.currentTimeMillis();

        String forcast = "";
        for (int i = 0; i < 3; i++) {
            forcast = cityService.cityForcast(city);
            log.info("----CONTROLLER RESULT-" + (i+1) +  ": " + forcast);
        }

        long end = System.currentTimeMillis();

        log.info("Time spend: " + (end - start));

        return city + " 's forcast: " + forcast;
    }
}
